package com.lucy.starter.exception;

import com.lucy.starter.constant.HttpStatus;
import com.lucy.starter.domain.ResponseDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.stereotype.Component;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;

import java.io.FileNotFoundException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kindear
 * 通用异常处理规则
 */
@Slf4j
@Component
public class CommonExceptionRule implements ExceptionRule{
    @Override
    public ResponseDTO<Object> exceptionHandler(Exception e) {
        //http 请求方式错误
        if(e instanceof HttpRequestMethodNotSupportedException){
            return ResponseDTO.wrap(HttpStatus.METHOD_NOT_ALLOWED);
        }
        // 文件 Not Found
        if (e instanceof FileNotFoundException){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND);
        }
        // 参数类型错误
        if (e instanceof TypeMismatchException) {
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST);
        }

        // json 格式错误
        if (e instanceof HttpMessageNotReadableException) {
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST);
        }

        // 参数校验未通过
        if (e instanceof MethodArgumentNotValidException) {
            List<FieldError> fieldErrors = ((MethodArgumentNotValidException) e).getBindingResult().getFieldErrors();
            List<String> msgList = fieldErrors.stream().map(FieldError :: getDefaultMessage).collect(Collectors.toList());
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST, String.join(",", msgList));
        }

        //自定义异常
        if(e instanceof BusinessException){
            ResponseDTO<Object> res = new ResponseDTO<Object>();
            res.setCode(((BusinessException) e).getCode());
            res.setMsg(e.getMessage());
            // 2022-12-29 异常应该标记为失败
            res.setSuccess(false);
            return res;
        }
        /*
         * 异步异常
         */
        if(e instanceof AsyncBusinessException){
            ResponseDTO<Object> res = new ResponseDTO<Object>();
            res.setCode(((AsyncBusinessException) e).getCode());
            res.setMsg(e.getMessage());
            res.setSuccess(false);
            return res;
        }
        return null;
    }
}
